;;;; init-xml - settings for work with XML based files 
;;;;
;;;;  Evgeniy Sharapov, evgeniy.sharapov@gmail.com 
;;;;
;;;;
(require 'cl)
(load-library "rng-auto") 
(load-library "hideshow")

(setq-default
 ;; Treat elements and contents like S-expressions! Oh, the magic. 
 ;; (if you know S-expression movement commands, it's great) 
 nxml-sexp-element-flag t
 ;; Whenever you type </ it will fill out the rest. 
 nxml-slash-auto-complete-flag t
 )
;; Causes files with extensions .xml .xsl .rng .xhtml .html and .tal 
;; to invoke nxml-mode. 
(setq auto-mode-alist 
      (cons '("\\.\\(xml\\|xsl\\|rng\\|tal\\)\\'" . nxml-mode) 
            (remove-if (lambda (x) (eq (cdr x) 'html-mode)) auto-mode-alist)))
;; another way to recognize XML files 
(push '("<\\?xml" . nxml-mode) magic-mode-alist)
;; load hide show modes 

(defun my-nxml-mode-hook ()
  (local-set-key "\C-c/" 'nxml-finish-element)
  (local-set-key [return] 'newline-and-indent)
  (auto-fill-mode)
  (rng-validate-mode)
  (unify-8859-on-decoding-mode)
  (setq ispell-skip-html t)
  (hs-minor-mode 1)
  )
(add-hook 'nxml-mode-hook 'my-nxml-mode-hook)

;;;;;;;;;;;;;;;;;;;;;; HTML ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; nxhtml stuff
;; (setq mumamo-chunk-coloring 'submode-colored
;;       nxhtml-skip-welcome t
;;       indent-region-mode t
;;       rng-nxml-auto-validate-flag nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun pretty-print-xml (begin end)
  "Pretty format XML markup"
  (save-excursion
    (nxml-mode)
    (goto-char begin)
    (while (search-forward-regexp "\>[ \\t]*\<" nil t) 
      (backward-char) (insert "\n"))
    (indent-region begin end))
  (message "Ah, much better!"))

(defun pretty-print-xml-region (begin end)
  "Pretty format XML markup in region. You need to have nxml-mode
http://www.emacswiki.org/cgi-bin/wiki/NxmlMode installed to do
this.  The function inserts linebreaks to separate tags that have
nothing but whitespace between them.  It then indents the markup
by using nxml's indentation rules."
  (interactive "r")
  (pretty-print-xml begin end))

(defun pretty-print-xml-buffer ()
  "Formats whole buffer containing XML"
  (interactive)
  (pretty-print-xml-region (point-min) (point-max)))

(provide 'init-xml)
